import { Ref, useState, useRef, useEffect, useContext } from 'react';
import { Button, Row, Col } from 'antd';
import lodash from 'lodash';
import { NeedUpdateContext } from '../common/NeedContext';
import { MaterialService } from '../services/MaterialService';
import { OneModal } from '@/components/one-ui';
import { IOneModalRef } from '@/pages/type';
import { onCloseModalCommon } from '@/utils';

import { connect } from 'umi';
import { UpdateNeedMaterialModalRight } from './UpdateNeedMaterialModalRight';
import { UpdateNeedMaterialModalLeft } from './UpdateNeedMaterialModalLeft';

import { getMaterialTableColumns } from '../mconfig';
import { UpdateNeedMaterialAddModal } from './UpdateNeedMaterialAddModal';
import { IActionEnum } from '../common/NeedReducer';

/**
 * @UpdateNeedMaterialModal 物料选择弹窗组件
 * @param onClose 关闭物料弹窗
 * @param onSave 保存选中物料数据
 * @returns
 */
// React.FC<NeedUpdateAPI.IUpdateNeedMaterialModal>
const UpdateNeedMaterialModal = ({ curRes, onClose, onSave }: Record<string, any>) => {
  /** 样式 */
  const prefixCls = 'need-update-';

  /** 是否点击新增物料 */
  const [isShowAddMateril, setIsShowAddMateril] = useState<boolean>(false);

  /** 页面需求详情选中的物料 */
  const { materialList, dispatch, dataSource } = useContext(NeedUpdateContext);

  /** 弹框ref */
  const reloadLayoutRef: Ref<IOneModalRef> = useRef(null);

  /** 表格选中内容 */
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);

  /** 表格选中record */
  const [selectRows, setSelectRows] = useState<Record<string, any>[]>([]);

  /** 选中树的key */
  const [selectKeys, setSelectKeys] = useState<React.Key[]>([]);

  /** 左侧类型树搜索 */
  const [typeTreeSearchObj, setTypeTreeSearchObj] = useState<Record<string, any>>({
    searchValue: '',
    expandedKeys: [],
    // autoExpandParent: false,
  });

  /** 获取物料列表 */
  const { getMaterialRun, getMaterialLoading, getMaterialDataSource, getMaterialTableProps, manageTableParams } = MaterialService().getMaterialService({
    curRes,
  });

  /**回显物料数据*/
  useEffect(() => {
    /** dateGrid 将物料id赋值给新字段【materialIDS】*/
    const newMaterialList = getMaterialDataSource?.map((item: Record<string, any>) => {
      /**在物料表中，物料id是id*/
      return { ...item, materialIDS: item?.id, materialID: item?.id, materialName: item?.fullName };
    });

    /** 克隆一份数据 */
    const tempData = lodash.cloneDeep(newMaterialList);
    if (materialList && materialList?.length && tempData?.length) {
      /** 详情数据返回的物料信息，保存key值反显，保存row存储数据 */
      let Keys: any[] = [];
      let Rows: any[] = [];
      materialList?.forEach((item) => {
        Keys?.push(item?.materialID);
        Rows?.push({ ...item, materialIDS: item?.materialID || item?.materialIDS });
      });

      /** 保存id和数据，反选中时候要用到 */
      setSelectedRowKeys(Keys);
      setSelectRows(Rows);

      /** 需求详情物料数据修改后数据同步到弹窗接口获取的数据 */
      Rows?.forEach((target) => {
        tempData.map((item: Record<string, any>, index: number) => {
          if (item.materialIDS == target.materialIDS) {
            //【预估单价（元）】
            tempData[index]['expectPrice'] = target?.expectPrice;
            //【需求数量】
            tempData[index]['expectNum'] = target?.expectNum;
            //【预估总价（元）】
            tempData[index]['expectSum'] = target?.expectSum;
            //【是否进口】
            tempData[index]['importFlag'] = target?.importFlag;
            //【是否单一来源】
            tempData[index]['singleFlag'] = target?.singleFlag;
            //【计划采购时间】
            tempData[index]['expectTime'] = target?.expectTime;
          }
        });
      });
      /** 数据派发reducer */
      dispatch({
        type: IActionEnum.UPDATE_DATASOURCE,
        payload: tempData,
      });
    } else {
      /** 数据派发reducer */
      dispatch({
        type: IActionEnum.UPDATE_DATASOURCE,
        payload: tempData,
      });
    }
  }, [getMaterialDataSource, materialList]);

  /**保存选中物料 */
  const changeSure = () => {
    const newRows = selectRows?.map((item) => {
      let newObj = { ...item };
      // 设置新数据的默认值
      if (!('importFlag' in item)) {
        newObj.importFlag = 0;
      }
      if (!('singleFlag' in item)) {
        newObj.singleFlag = 0;
      }
      if (!('isPlatform' in item)) {
        newObj.isPlatform = 0;
      }
      return newObj;
    });
    onSave(newRows);
    onCloseModalCommon(reloadLayoutRef);
  };

  /**GY: 处理表格的多次选中*/
  const rowSelection = {
    selectedRowKeys,
    onSelect: (record: any, selected: any) => {
      if (selected) {
        /** 添加 */
        setSelectedRowKeys([...selectedRowKeys, record?.materialIDS]); // 保存key
        setSelectRows([...selectRows, record]); // 保存record
      } else {
        /** 去除 */
        const rowsList = selectRows?.filter((item) => record?.materialIDS != item?.materialIDS);
        setSelectedRowKeys(rowsList?.map((i: Record<string, any>) => i?.materialIDS));
        setSelectRows(rowsList);
      }
    },
    onSelectAll: (selected: any, selectedRows: any, changeRows: any) => {
      let dataKeys: any[] = []; // 当前table渲染的数据key集合
      dataSource?.forEach((item: Record<string, any>) => {
        dataKeys?.push(item?.materialIDS);
      });
      if (selected) {
        //全选
        // 两个key合并去重
        let keylist = Array.from(new Set([...dataKeys, ...selectedRowKeys]));
        setSelectedRowKeys(keylist);
        // 处理record
        setSelectRows([...selectRows, ...changeRows]);
      } else {
        //全不选
        // 处理key
        let newarr: any[] = selectedRowKeys?.filter((item) => {
          return !dataKeys?.includes(item);
        });
        setSelectedRowKeys(newarr);
        /**
         * 处理row 这里的changeRows代表被取消的rows集合
         * {keys} 拿的是被取消的rows集合的id集合
         * 再已经选择的数据中进行过滤
         * */
        let keys: any[] = [];
        changeRows?.forEach((item: any) => {
          keys?.push(item?.materialIDS);
        });
        const newRows = selectRows?.filter((item) => {
          return keys?.indexOf(item?.materialIDS) == -1;
        });
        setSelectRows(newRows);
      }
    },
    getCheckboxProps: (record: Record<string, any>) => ({
      disabled: record?.state != 2,
    }),
  };

  /**底部按钮*/
  const footerRender = () => {
    return (
      <>
        <Button onClick={() => onCloseModalCommon(reloadLayoutRef)}>取消</Button>
        {/* 有【新增物料】和【申请物料】的权限 */}
        {curRes?.['/materialController/add'] && curRes?.['/materialController/applyMaterial'] && (
          <Button type={'primary'} onClick={() => setIsShowAddMateril(!isShowAddMateril)}>
            添加
          </Button>
        )}
        <Button type={'primary'} onClick={changeSure}>
          确认
        </Button>
      </>
    );
  };

  /**左侧数据点击事件过滤数据*/
  const onSelectLeftTree = (val: string | null) => {
    if (val) {
      getMaterialRun({ ...manageTableParams, materialType: val });
    } else {
      getMaterialRun({ ...manageTableParams, materialType: null });
    }
  };

  return (
    <>
      <OneModal
        open={true}
        getContainer={false}
        ref={reloadLayoutRef}
        title={'物料列表'}
        className={prefixCls + 'oneModal'}
        width={1500}
        onCancel={() => {
          onClose(false);
        }}
        footer={footerRender()}
        bodyStyle={{
          padding: '2px 8px',
          height: '700px',
          display: 'flex',
          flexDirection: 'column',
        }}
        centered
      >
        <Row gutter={[10, 16]} className={prefixCls + 'oneModal-oneModalBox'}>
          <Col span={6}>
            <UpdateNeedMaterialModalLeft
              prefixCls={prefixCls}
              onSelect={onSelectLeftTree}
              onTreeKey={{ selectKeys, setSelectKeys }}
              leftTreeSeatchObj={{ typeTreeSearchObj, setTypeTreeSearchObj }}
            />
          </Col>
          <Col span={18}>
            <UpdateNeedMaterialModalRight
              prefixCls={prefixCls}
              selectedRowKeys={selectedRowKeys}
              getMaterialRun={(res, type) => {
                if (type && type == 'reset') {
                  setSelectKeys([]);
                  setTypeTreeSearchObj({ searchValue: '', expandedKeys: [] });
                  getMaterialRun({});
                } else {
                  getMaterialRun({ ...res, materialType: selectKeys?.toString() || null });
                }
              }}
              getMaterialLoading={getMaterialLoading}
              dataSource={dataSource}
              rowSelection={rowSelection}
              getMaterialTableColumns={getMaterialTableColumns}
              getMaterialTableProps={getMaterialTableProps}
            />
          </Col>
        </Row>
      </OneModal>

      {/* 新增物料弹窗 */}
      {isShowAddMateril && <UpdateNeedMaterialAddModal prefixCls={prefixCls} onClose={() => setIsShowAddMateril(false)} onOk={() => getMaterialRun({})} />}
    </>
  );
};

export default connect(({ baseLogin }: Record<string, any>) => ({
  curRes: baseLogin?.permissions,
}))(UpdateNeedMaterialModal);
